package com.ufida.ids.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hereway.core.servlet.BaseServlet;
import com.hereway.core.util.ParamUtils;
import com.ufida.ids.model.StaffModel;
import com.ufida.ids.service.IStaffService;
import com.ufida.ids.util.CipherUtil;
import com.ufida.ids.util.Constants;
import com.ufida.ids.util.DateUtil;
import com.ufida.ids.util.ExtUtil;
import com.ufida.ids.util.StringUtil;
import com.ufida.ids.util.upload.UpLoad;

public class StaffServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(StaffServlet.class);

	@Autowired
	private IStaffService staffService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StaffServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		//获取操作类型
		String action = ParamUtils.getParameter(request, "action");
		logger.debug("action:"+action);
		if ("getStaffListByCon".equals(action)){
			getStaffListByCon(request, response);
		}else if("getStaffByStaffId".equals(action)){
			getStaffByStaffId(request, response);
		}else if("add".equals(action)){
			add(request, response);
		}else if("edit".equals(action)){
			edit(request, response);
		}else if("delete".equals(action)){
			delete(request, response);
		}else if("active".equals(action)){
			active(request, response);
		}else if("unactive".equals(action)){
			unactive(request, response);
		}else if("resetPWD".equals(action)){
			resetPWD(request, response);
		}else if("verifyOldPWD".equals(action)){
			verifyOldPWD(request, response);
		}else if("modifyPWD".equals(action)){
			modifyPWD(request, response);
		}
	}
	
	private void getStaffListByCon(HttpServletRequest request, HttpServletResponse response) {
		//分页参数
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));	
		int pageNum = Integer.parseInt(request.getParameter("page"));	
		
		String condition = request.getParameter("condition");
		JSONObject o = JSONObject.fromObject(condition);
		String currentOrgId =  o.optString("currentOrgId");
		String staffName =  o.optString("staffName");
		String loginName =  o.optString("loginName");
		String email =  o.optString("email");
		
		try {
			String retStr = staffService.getStaffListByConPagging(currentOrgId, loginName, staffName, email, pageNum);
			writeResponse(response, retStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getStaffByStaffId(HttpServletRequest request, HttpServletResponse response) {
		//分页参数
		String staffId = request.getParameter("staffId");
		try {
			String retStr = ""; 
			StaffModel staff = staffService.get(Long.parseLong(staffId));
			
			staff.setCreateTsStr(DateUtil.getDateStrPattern1(staff.getCreateTs()));
			if(null != staff.getBirthday()){
				staff.setBirthdayStr(DateUtil.getDateStrPattern2(staff.getBirthday()));
			}
			List l = new ArrayList();
			l.add(staff);
			retStr = ExtUtil.getJosonStr(l,new String[]{"birthday","userMappingModels", "postStaffModels"},1);
			System.out.println("retStr:"+retStr);
			writeResponse(response, retStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[add staff...]");
		HashMap paraValueM = new HashMap();
		boolean flag = true;
		try{
			UpLoad upload = new UpLoad(request);
	        String trueFileName = upload.getUpFile(paraValueM);
	        StaffModel staffModel = new StaffModel();
	        buildStaffObject(staffModel,paraValueM,trueFileName,"add");
	        staffService.save(staffModel);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		writeResponse(response, flag);
	}
	
	private void edit(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[edit staff...]");
		boolean flag = true;
		HashMap paraValueM = new HashMap();
		try{
			UpLoad upload = new UpLoad(request);
			String trueFileName = upload.getUpFile(paraValueM);
			String staffId = paraValueM.get("staffId")+"";
			StaffModel staffModel = staffService.get(Long.parseLong(staffId));
			buildStaffObject(staffModel,paraValueM,trueFileName,"edit");
			staffService.update(staffModel);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		writeResponse(response, flag);
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[delete staff...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<StaffModel> l = staffService.find(idStr);
			for(StaffModel staffModel:l){
				staffModel.setEntityStatus(Constants.STATUS_DEL);
				staffService.update(staffModel);
			}
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	private void active(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[active staff...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<StaffModel> l = staffService.find(idStr);
			for(StaffModel staffModel:l){
				staffModel.setEntityStatus(Constants.STATUS_ACTIVE);
				staffService.update(staffModel);
			}
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	private void unactive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[unactive staff...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<StaffModel> l = staffService.find(idStr);
			for(StaffModel staffModel:l){
				staffModel.setEntityStatus(Constants.STATUS_UNACTIVE);
				staffService.update(staffModel);
			}
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	private void resetPWD(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[resetPWD staff...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<StaffModel> l = staffService.find(idStr);
			for(StaffModel staffModel:l){
				staffModel.setPassword(Constants.INIT_PWD);
				staffService.update(staffModel);
			}
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	private void verifyOldPWD(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[verifyOldPWD staff...]");
		String staffId = ParamUtils.getParameter(request, "staffId");
		String oldPWD = ParamUtils.getParameter(request, "oldPWD");
		String retStr = "";
		try {
			StaffModel staffModel = staffService.get(Long.parseLong(staffId));
			String password = staffModel.getPassword();
			System.out.println("password:"+password);
			System.out.println("oldPWD:"+oldPWD);
			if(CipherUtil.validatePassword(password, oldPWD)){
				retStr = ExtUtil.getJosonStr(true);
			}else{
				retStr = ExtUtil.getJosonStr(false);
			}
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	private void modifyPWD(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[verifyOldPWD staff...]");
		String staffId = ParamUtils.getParameter(request, "staffId");
		String newPWD = ParamUtils.getParameter(request, "newPWD");
		String retStr = "";
		try {
			StaffModel staffModel = staffService.get(Long.parseLong(staffId));
			staffModel.setPassword(CipherUtil.generatePassword(newPWD));
			staffService.update(staffModel);
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
		}
		writeResponse(response, retStr);
	}
	
	
	private static void buildStaffObject(StaffModel staffModel,Map paraValueM,String trueFileName,String action) throws ParseException{
		String staffCode = paraValueM.get("staffCode") ==  null?"":paraValueM.get("staffCode")+"";
        String loginName = paraValueM.get("loginName") ==  null?"":paraValueM.get("loginName")+"";
        String staffName = paraValueM.get("staffName") ==  null?"":paraValueM.get("staffName")+"";
        String sex = paraValueM.get("sex") ==  null?"":paraValueM.get("sex")+"";
        String birthday = paraValueM.get("birthday") ==  null?"":paraValueM.get("birthday")+"";
        String idcardNo = paraValueM.get("idcardNo") ==  null?"":paraValueM.get("idcardNo")+"";
        String orgName = paraValueM.get("orgName") ==  null?"":paraValueM.get("orgName")+"";
        String post = paraValueM.get("post") ==  null?"":paraValueM.get("post")+"";
        String workGroup = paraValueM.get("workGroup") ==  null?"":paraValueM.get("workGroup")+"";
        String tel = paraValueM.get("tel") ==  null?"":paraValueM.get("tel")+"";
        String address = paraValueM.get("address") ==  null?"":paraValueM.get("address")+"";
        String email = paraValueM.get("email") ==  null?"":paraValueM.get("email")+"";
        String mobile = paraValueM.get("mobile") ==  null?"":paraValueM.get("mobile")+"";
        String postcode = paraValueM.get("postcode") ==  null?"":paraValueM.get("postcode")+"";
        String problem = paraValueM.get("problem") ==  null?"":paraValueM.get("problem")+"";
        String answer = paraValueM.get("answer") ==  null?"":paraValueM.get("answer")+"";
        String password = paraValueM.get("password") ==  null?"":paraValueM.get("password")+"";
        String orgId = paraValueM.get("orgId") ==  null?"":paraValueM.get("orgId")+"";
		
		{
			staffModel.setStaffCode(staffCode);
			staffModel.setLoginName(loginName);
			staffModel.setStaffName(staffName);
			staffModel.setSex(Short.valueOf(sex));
			if(!"".equals(birthday)){
				staffModel.setBirthday(DateUtil.getDateByStr(birthday));
			}
			staffModel.setIdcardNo(idcardNo);
			if(!"".equals(orgId)){
				staffModel.setOrgId(Long.parseLong(orgId));
			}
			staffModel.setPostcode(postcode);
			staffModel.setTel(tel);
			staffModel.setAddress(address);
			staffModel.setEmail(email);
			staffModel.setMobile(mobile);
			staffModel.setProblem(problem);
			staffModel.setAnswer(answer);
			
			//对密码进行加密
			if("edit".equals(action)){//编辑
				staffModel.setPassword(CipherUtil.generatePassword(password));
			}else if("add".equals(action)){//新增，则填入初始密码
				staffModel.setPassword(CipherUtil.generatePassword(Constants.INIT_PWD));
			}
			
			staffModel.setCreateTs(new Date());
			staffModel.setModifiedTs(new Date());
			if(!"".equals(trueFileName)){
				staffModel.setPhoto(trueFileName);
			}
			staffModel.setCreator(Constants.TEMP_CREATOR);
			staffModel.setEntityStatus(Constants.STATUS_ACTIVE);
			
		}
	}
}
